<template>
  <el-dialog @close="close" v-model="dialogVisible" :title="title" width="50%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="ruleForm.nickName" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-select v-model="ruleForm.sex" placeholder="请选择性别">
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="归属部门" prop="deptId">
        <el-tree-select
          ref="tree"
          v-model="ruleForm.deptId"
          :data="deptOptions"
          placeholder="请选择上级部门"
          check-strictly
          :render-after-expand="false"
          highlight-current
          style="width: 100%"
        >
          <template #default="{ data: { label, length } }">
            {{ label }}
            <span style="color: gray" v-if="length > 0">({{ length }})</span>
          </template>
        </el-tree-select>
      </el-form-item>
      <el-form-item label="关联角色" prop="roleIds">
        <el-select ref="roleRef" v-model="ruleForm.roleIds" multiple placeholder="请选择角色">
          <el-option
            v-for="item in roleOptions"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
            :disabled="item.status == 1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="roleIds">
        <el-select v-model="ruleForm.postIds" multiple placeholder="请选择角色">
          <el-option
            v-for="item in postOptions"
            :key="item['postId']"
            :label="item['postName']"
            :value="item['postId']"
            :disabled="item['status'] == 1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="ruleForm.phonenumber" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email" placeholder="请输入邮箱号" />
      </el-form-item>
      <el-form-item label="账户密码" prop="password" v-if="!ruleForm.userId">
        <el-input
          v-model="ruleForm.password"
          placeholder="请输入账户密码,如果不输入默认123456"
          type="password"
          clearable
        />
      </el-form-item>
      <el-form-item label="用户状态">
        <el-radio-group v-model="ruleForm.status">
          <el-radio
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入用户描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleClose(ruleFormRef)"> 确定 </el-button>
        <el-button type="success" @click="dialogVisible = false"> 取消 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { FormInstance } from 'element-plus'
  import { getCurrentInstance, onBeforeMount, reactive, ref } from 'vue'
  import {
    reqUserAddUrl,
    reqUserEditUrl, reqUserGetInfoByIdUrl
  } from "@/api/system/user";

  const { proxy }: any = getCurrentInstance()
  const ruleFormRef = ref<FormInstance>()
  const dialogVisible = ref<boolean>(false)
  const title = ref('新增用户')
  const roleOptions = ref([]) // 角色选项
  const postOptions = ref([]) // 岗位选项
  const deptOptions = ref([]) // 部门选项
  const roleRef = ref()
  let $emit = defineEmits(['getUserListPage'])
  const rules = reactive({
    nickname: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
    ],
    username: [{ required: true, message: '请输入', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  })

  /*form表单*/
  const ruleForm = reactive({
    userId: undefined,
    username: '',
    nickName: null,
    sex: '男',
    roleIds: null,
    postIds: null,
    email: null,
    phonenumber: null,
    password: '123456',
    remark: null,
    status: '0',
    deptId: null,
  })

  function close() {
    ruleFormRef.value.resetFields() /*表单重置*/
  }

  /*查询出用户信息，部门树，角色树*/
  const show = async (item: any = {}) => {
    title.value = '新增用户'
    console.log('item', item)
    await reqUserGetInfoByIdUrl(item.userId).then((req: any) => {
      console.log('item', req)
      if (req.code === 200) {
        let tree = proxy.$handleTree(req.depts, 'deptId')
        deptOptions.value = filterMethod(tree)
        roleOptions.value = req.roles
        postOptions.value = req.posts
      }
      /*编辑用户的操作*/
      if (item.userId) {
        title.value = '编辑用户'
        /*表单赋值*/
        Object.keys(req.data).forEach((key) => {
          console.log(key)
          ruleForm[key] = req.data[key]
        })
        ruleForm.roleIds = req.roleIds
        ruleForm.postIds = req.postIds
      }
    })
    dialogVisible.value = true
  }
  /*将该树进行过滤*/
  const filterMethod = (tree: any) => {
    const filteredTree = tree.map((t: any) => {
      if (t.children) {
        t.children = filterMethod(t.children) // 递归调用 filterMethod
      }
      return {
        value: t.deptId,
        label: t.deptName,
        children: t.children ? t.children : [],
      }
    })
    return filteredTree // 返回过滤后的树节点数组
  }

  const handleClose = async (done: () => void) => {
    await ruleFormRef.value.validate(async (valid: any, fields: any) => {
      if (valid) {
        if (!ruleForm.userId) {
          await reqUserAddUrl(ruleForm).then((req: any) => {
            if (req.code === 200) {
              proxy.$modal.msgSuccess('添加成功！')
              dialogVisible.value = false
              $emit('getUserListPage')
            } else {
              proxy.$modal.msgError(req.message != null ? req.message : '添加失败！')
              return
            }
          })
        } else {
          await reqUserEditUrl(ruleForm).then((req: any) => {
            if (req.code === 200) {
              proxy.$modal.msgSuccess('修改成功！')
              dialogVisible.value = false
              $emit('getUserListPage')
            } else {
              proxy.$modal.msgError(req.message != null ? req.message : '修改失败！')
              return
            }
          })
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  /*在组件挂载之前执行*/
  onBeforeMount(() => {
    //getDeptTree();
  })
  defineExpose({
    show,
  })
</script>

<script lang="ts">
  export default {
    dicts: ['sys_normal_disable', 'sys_user_sex'],
  }
</script>
<style lang="scss" scoped></style>
